package cn.wolfcode.shiro.web.controller;

import cn.wolfcode.shiro.dao.IPermissionDAO;
import cn.wolfcode.shiro.domain.Permission;
import cn.wolfcode.shiro.realm.PermissionName;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@Controller
public class PermissionController {
   //请求映射处理映射器
   //springmvc在启动时候将所有贴有请求映射标签：RequestMapper方法收集起来封装到该对象中
    @Autowired
    private RequestMappingHandlerMapping rmhm;

    @Autowired
    private IPermissionDAO iPermissionDAO;
    @RequestMapping("/reload")
    public String reload() throws  Exception{
        //首先查询出所有的权限表达式
        List<String> allResources = iPermissionDAO.getAllResources();

        //1:获取controller中所有带有@RequestMapper标签的方法
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhm.getHandlerMethods();

        Collection<HandlerMethod> values = handlerMethods.values();
        for (HandlerMethod method:values){
            //2.遍历所有方法，判断当前方法是否贴有@RequiresPermissions权限控制标签
            RequiresPermissions methodAnnotation = method.getMethodAnnotation(RequiresPermissions.class);
            //3：如果有，解析得到权限表达式，封装成Permission对象保存到Permission表中
            if (methodAnnotation!=null){
                String s = methodAnnotation.value()[0];
                //去除重复的
                if (allResources.contains(s)){
                    continue;
                }
                Permission permission=new Permission();
                permission.setResource(s);
                permission.setName(method.getMethodAnnotation(PermissionName.class).value());
                iPermissionDAO.save(permission);

            }

        }



        return "main";
    }

}
